package com.dxw.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DbConn {
	
	//创建连接池
	private static DataSource dataSource;
	
	static {
		//通过druid创建一个连接池
		try {
			dataSource = DruidDataSourceFactory
					.createDataSource(getProperties("com/dxw/config/db.properties"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Properties getProperties(String fileName) {
		Properties p = new Properties();
		//加载文件的路径
		//动态的获取文件的路径
		String path = DbConn.class.getResource("/").getPath();
		try {
			//decode:将url编码进行解码
			path = URLDecoder.decode(path, "UTF-8") + fileName;
			//加载这个路径
			p.load(new FileInputStream(path));
			//System.out.println(path);
			return p;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private DbConn() {}
	
	public static DataSource getDataSource() {
		return dataSource;
	}

	public static void main(String[] args) {
		try {
			Connection conn1 = DbConn.getDataSource().getConnection();
			System.out.println("conn1="+conn1);
			Connection conn2 = DbConn.getDataSource().getConnection();
			System.out.println("conn2="+conn2);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
